package com.smartHome.controller;

import com.smartHome.pojo.dto.UserDTO;
import com.smartHome.pojo.entity.Result;
import com.smartHome.pojo.entity.User;
import com.smartHome.service.UserService;
import com.smartHome.utils.JwtUtil;
import com.smartHome.utils.Md5Util;
import com.smartHome.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;



    @PostMapping("/login")
    public Result<String> login(@RequestBody User user) {
        //根据用户名查询用户
        User loginUser = userService.findByEmail(user.getEmail());
        //该用户是否存在
        if (loginUser == null) {
            return Result.error("邮箱不正确");
        }
        else {
            //判断密码是否正确
            if (Md5Util.getMD5String(user.getPassword()).equals(loginUser.getPassword())) {
                //登录成功
                Map<String,Object> claim = new HashMap<>();
                claim.put("id",loginUser.getUserId());
                claim.put("username",loginUser.getUsername());
                claim.put("email",loginUser.getEmail());
                String token = JwtUtil.genToken(claim);
                return Result.success(token);
            }
            return Result.error("密码错误");
        }
    }

    /**
     * 注册用户
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        //注册
        userService.register(user);

        return Result.success();
    }

    @GetMapping("/register/{email}")
    public Result  judge_email(@PathVariable String email){
        //查询用户
        User byEmail = userService.findByEmail(email);
        if (byEmail != null) {
            return Result.error("邮箱已被占用");
        }
        return Result.success();
    }

    //获取用户详细信息
    @GetMapping("/userInfo")
    public Result<User> getUser() {
        //获取用户email
        Map<String, Object> map = ThreadLocalUtil.get();
        String email = (String) map.get("email");

        User user = userService.findByEmail(email);

        //剔除用户密码
        user.setPassword("");

        return Result.success(user);
    }

    //修改用户信息
    @PostMapping("/update")
    public Result<User> update(@RequestBody UserDTO userDTO) {

        userService.update(userDTO);

        return Result.success();
    }

}
